package juc;


/**
 * 模拟商品秒杀并发问题
 */
public class Demo4 {

    public static void main(String[] args) {
        Goods goods = new Goods();

        new Thread(()->{
            //顾客线程
            System.out.println("顾客线程：");
            goods.buyThisGoods();
            System.out.println("顾客买好了！");
        },"customer").start();

        new Thread(()->{
            //店家线程
            System.out.println("店家线程：");
            goods.addThisGoods();
            System.out.println("店家新增好了！");
        },"restaurant").start();
    }

}

class Goods{
    private String name = "商品1";
    /**
     * 库存
     */
    private int count = 0;

    public synchronized void buyThisGoods() {
        while (count==0){
            try {
                //库存为0，等待
                System.out.println("buyThisGoods等待");
                this.wait();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        //库存不为0，商品库存减1
        count--;
        System.out.println("buyThisGoods: " + Thread.currentThread().getName() + "=>" + name + ":" + count);
        //通知其他线程
        this.notifyAll();
    }

    public synchronized void addThisGoods(){
        count++;
        System.out.println("addThisGoods: " + Thread.currentThread().getName() + "=>" + name + ":" + count);
        //通知其他线程
        this.notifyAll();
    }
}